import 'package:flutter/material.dart';

// void main() {
//   runApp(const SliverAnimatedOpacityPage());
// }

class SliverAnimatedOpacityPage extends StatelessWidget {
  const SliverAnimatedOpacityPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: SliverAnimatedOpacityDemo(),
    );
  }
}

class SliverAnimatedOpacityDemo extends StatefulWidget {
  const SliverAnimatedOpacityDemo({super.key});

  @override
  State<SliverAnimatedOpacityDemo> createState() =>
      _SliverAnimatedOpacityDemoState();
}

class _SliverAnimatedOpacityDemoState
    extends State<SliverAnimatedOpacityDemo> {
  double _opacity = 1.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification) {
          if (notification.metrics.axis == Axis.vertical) {
            setState(() {
              // 滚动距离越大，透明度越低
              _opacity = (100 - notification.metrics.pixels) / 100;
              if (_opacity < 0) _opacity = 0;
              if (_opacity > 1) _opacity = 1;
            });
          }
          return true;
        },
        child: CustomScrollView(
          slivers: [
            SliverAnimatedOpacity(
              duration: const Duration(milliseconds: 300),
              opacity: _opacity,
              sliver: SliverToBoxAdapter(
                child: Container(
                  height: 120,
                  color: Colors.blue,
                  alignment: Alignment.center,
                  child: const Text(
                    "头部渐隐",
                    style: TextStyle(color: Colors.white, fontSize: 24),
                  ),
                ),
              ),
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                    (context, index) => ListTile(
                  title: Text("Item #$index"),
                ),
                childCount: 30,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
